﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;

namespace Grauers.SharePointGoogleChart.InteractiveDiagram
{
    [ToolboxItemAttribute(false)]
    public class InteractiveDiagram : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/Grauers.SharePointGoogleChart/InteractiveDiagram/InteractiveDiagramUserControl.ascx";
        private const string CATEGORY = "Grauers";

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
   System.Web.UI.WebControls.WebParts.WebDisplayName("Chart Width"),
   System.Web.UI.WebControls.WebParts.WebDescription("Width of Chart"),
   System.Web.UI.WebControls.WebParts.Personalizable(
   System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
   System.ComponentModel.Category(CATEGORY),
   System.ComponentModel.DefaultValue("")
   ]
        public int ChartWidth { get; set; }

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
     System.Web.UI.WebControls.WebParts.WebDisplayName("Chart Height"),
     System.Web.UI.WebControls.WebParts.WebDescription("Height of Chart"),
     System.Web.UI.WebControls.WebParts.Personalizable(
     System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
     System.ComponentModel.Category(CATEGORY),
     System.ComponentModel.DefaultValue("")
     ]
        public int ChartHeight { get; set; }


        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
        System.Web.UI.WebControls.WebParts.WebDisplayName("List URL"),
        System.Web.UI.WebControls.WebParts.WebDescription("Url to your list"),
        System.Web.UI.WebControls.WebParts.Personalizable(
        System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
        System.ComponentModel.Category(CATEGORY),
        System.ComponentModel.DefaultValue("")
        ]
        public string ListUrl { get; set; }

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
       System.Web.UI.WebControls.WebParts.WebDisplayName("View of list"),
       System.Web.UI.WebControls.WebParts.WebDescription("Name of view"),
       System.Web.UI.WebControls.WebParts.Personalizable(
       System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
       System.ComponentModel.Category(CATEGORY),
       System.ComponentModel.DefaultValue("")
       ]
        public string ListView { get; set; }

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
      System.Web.UI.WebControls.WebParts.WebDisplayName("Columns"),
      System.Web.UI.WebControls.WebParts.WebDescription("Separate with comma example (colulmn1 (string),colulmn2 (number),column3(number))"),
      System.Web.UI.WebControls.WebParts.Personalizable(
      System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
      System.ComponentModel.Category(CATEGORY),
      System.ComponentModel.DefaultValue("")
      ]
        public string Columns { get; set; }

        public enum ChartTypes : int
        {
            ColumnChart = 0,
            LineChart = 1,
            PieChart = 2,
            AreaChart = 3,
            BarChart = 4
        }
        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
       System.Web.UI.WebControls.WebParts.WebDisplayName("Chart Types"),
       System.Web.UI.WebControls.WebParts.WebDescription("Choose chart type"),
       System.Web.UI.WebControls.WebParts.Personalizable(
       System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
       System.ComponentModel.Category(CATEGORY),
       System.ComponentModel.DefaultValue("")
       ]
        public ChartTypes DisplayChartTypes { get; set; }

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
      System.Web.UI.WebControls.WebParts.WebDisplayName("Chart Title"),
      System.Web.UI.WebControls.WebParts.WebDescription("Title of Chart"),
      System.Web.UI.WebControls.WebParts.Personalizable(
      System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
      System.ComponentModel.Category(CATEGORY),
      System.ComponentModel.DefaultValue("")
      ]
        public string ChartTitle { get; set; }

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
      System.Web.UI.WebControls.WebParts.WebDisplayName("Chart XTitle"),
      System.Web.UI.WebControls.WebParts.WebDescription("Title of Y Chart"),
      System.Web.UI.WebControls.WebParts.Personalizable(
      System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
      System.ComponentModel.Category(CATEGORY),
      System.ComponentModel.DefaultValue("")
      ]
        public string ChartYTitle { get; set; }

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
      System.Web.UI.WebControls.WebParts.WebDisplayName("Chart YTitle"),
      System.Web.UI.WebControls.WebParts.WebDescription("Title of X Chart"),
      System.Web.UI.WebControls.WebParts.Personalizable(
      System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
      System.ComponentModel.Category(CATEGORY),
      System.ComponentModel.DefaultValue("")
      ]
        public string ChartXTitle { get; set; }

        protected override void CreateChildControls()
        {
            // Get Intractive chart user control
            InteractiveDiagramUserControl control = (InteractiveDiagramUserControl)Page.LoadControl(_ascxPath);

            // Some controls
            Literal JavaScriptLiteral = (Literal)control.FindControl("JavaScriptLiteral");
            Label MessageLabel = (Label)control.FindControl("MessageLabel");

            // Try to do something fun
            try
            {
                // List url empty or null?
                if (ListUrl != null && ListUrl.Length > 0)
                {
                    // Get site and open the web
                    SPSite site = new SPSite(ListUrl);
                    SPWeb web = site.OpenWeb();

                    // Get list
                    SPList list = web.GetListFromUrl(ListUrl);
                    SPView view;

                    // Does the view exist?
                    if (ListView == null || ListView.Length == 0)
                        view = list.DefaultView;
                    else
                        view = list.Views[ListView];

                    SPQuery query = new SPQuery();
                    query.Query = view.Query;


                    SPListItemCollection listCollection = list.GetItems(query);

                    // Literal prop
                    StringBuilder JavaScriptDiagramStringBuilder = new StringBuilder();
                    JavaScriptDiagramStringBuilder.Append(@"
                    <script type='text/javascript' src='http://www.google.com/jsapi'></script> 
                    <script type='text/javascript'> 
                    google.load('visualization', '1', {packages:['corechart']}); 
                    google.setOnLoadCallback(drawChart); 
                    function drawChart() { 
                    var data = new google.visualization.DataTable(); ");

                    // Set columns
                    string[] columns = Columns.Split(',');

                    int i = 0;
                    foreach (string column in columns)
                    {
                        JavaScriptDiagramStringBuilder.AppendFormat("data.addColumn('{0}', '{1}');", i == 0 ? "string" : "number", column);
                        i++;
                    }

                    // Add rows
                    JavaScriptDiagramStringBuilder.AppendFormat("data.addRows({0});", listCollection.Count);

                    int rowPos = 0;
                    foreach (SPListItem item in listCollection)
                    {
                        int columnPos = 0;
                        foreach (string column in columns)
                        {
                            JavaScriptDiagramStringBuilder.AppendFormat("data.setValue({0}, {1}, {3}{2}{3});", rowPos, columnPos, item[item.Fields.GetField(column.Trim()).Id].ToString().Replace("'", "").Replace("float;#", "").Replace(",", "."), columnPos == 0 ? "'" : "");
                            columnPos++;
                        }
                        rowPos++;

                    }

                    // Literal prop
                    if (ChartWidth == 0)
                        ChartWidth = 500;
                    if (ChartHeight == 0)
                        ChartHeight = 300;
                    // LineChart
                    string chartGuid = Guid.NewGuid().ToString().Replace("-", "_");
                    JavaScriptDiagramStringBuilder.Append(@"var chart = new google.visualization." + DisplayChartTypes + @"(document.getElementById('chart" + chartGuid + @"')); 
                    chart.draw(data, {width: " + ChartWidth + ", height: " + ChartHeight + ", title: '" + ChartTitle + "', hAxis: {title: '" + ChartXTitle + @"', titleColor:'black'}
                    , vAxis: {title: '" + ChartYTitle + @"', titleColor:'black'} 
                                     }); 
                  } 
                </script><div id='chart" + chartGuid + "'></div> ");

                    // Set JavaScriptLiteral
                    JavaScriptLiteral.Text = JavaScriptDiagramStringBuilder.ToString();
                    MessageLabel.Visible = false;
                }
                else
                {
                    MessageLabel.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageLabel.Text = ex.Message;
            }
            Controls.Add(control);
        }
    }
}
